<?php
namespace app\admin\controller;

use app\admin\model\User as UserModel;
use Db;
use think\Controller;

/**
 * 用户分信息
 */
class Login extends Controller
{
    /*
    用户登录
     */
    public function index()
    {
        if ($this->request->post()) {
            $post = $this->request->post();

            $result = $this->validate($post, 'app\admin\validate\User.login');
            if (true !== $result) {
                return $this->error($result);
            }

            if (UserModel::login($post['user_name'], $post['password'])) {
                //登录数据处理
                return $this->success('登录成功,正在跳转...', 'admin/index/index');
            } else {
                return $this->error('用户名不存在,或密码错误');

            }
        }
        $userid = session('userid');
        if(!empty($userid)){return $this->redirect('Index/index');} //登录后默认跳转到登录后的页面
        return $this->fetch();
    }

    /**
     * 自定义验证码
     * @return [type] [description]
     */
    public function verify()
    {
        $config = [
            // 验证码字体大小
            'fontSize' => 30,
            // 验证码位数
            'length'   => 4,
            // 关闭验证码杂点
            'useNoise' => false,
        ];
        $captcha          = new \think\captcha\Captcha($config);
        $captcha->fontttf = '5.ttf';
        return $captcha->entry();
    }
/**
 * 权限提示
 * @param  [type] $c [description]
 * @param  [type] $a [description]
 * @return [type]    [description]
 */
    public function auth($c, $a)
    {
        $url   = $c . '/' . $a;
        $datas = Db::name('auth_rule')->where('name', $url)->find();
        if (!empty($datas)) {
            $data['u']    = cookie('username');
            $data['name'] = $datas['title'];
            $data['c']    = "";
            $data['a']    = "";
        } else {
            $data['c'] = $c;
            $data['a'] = $a;
            $data['u'] = cookie('username');
        }
        $data['code'] = -1;
        //return json_decode($data);

        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * 退出登录
     * @return [type] [description]
     */
    public function loginOut()
    {
       $userid =  session('userid');
        if (isset($userid)) {
            //addlog(session('userid'), "用户退出成功");
            session('userid', null);
            session('user_token', null);
            cookie('username', null);
            cookie('uid', null);
        }
        $this->redirect('Login/index');
    }

}
